//
//  DisclosureCell.m
//  iTunes Playlist Selector
//
//  Created by Keith Duncan on 22/05/2007.
//  Copyright 2007 BUOY. All rights reserved.
//

#import "DisclosureButton.h"

@implementation DisclosureButton

+ (Class)cellClass {
	return [DisclosureCell class];
}

+ (id)buttonWithRepresentedObject:(id)object {
	return [[[[self class] alloc] initWithRepresentedObject:object] autorelease];
}

- (id)initWithRepresentedObject:(id)object {
	[super initWithFrame:NSZeroRect];
	
	[self setTitle:nil];
	[self setBezelStyle:NSDisclosureBezelStyle];
	[self setButtonType:NSOnOffButton];
	[_cell setRepresentedObject:object];
	
	return self;
}

- (void)setRowHighlighted:(BOOL)highlighted {
	((DisclosureCell *)_cell).cellColor = (highlighted ? [NSColor whiteColor] : [NSColor colorWithCalibratedRed:(113.0/255.0) green:(125.0/255.0) blue:(142.0/255.0) alpha:1.0]);
	((DisclosureCell *)_cell).shadowColor = (highlighted ? [NSColor darkGrayColor] : [NSColor whiteColor]);
}

- (id)representedObject {
	return [(DisclosureCell *)_cell representedObject];
}

- (void)setRepresentedObject:(id)object {
	[(DisclosureCell *)_cell setRepresentedObject:object];
}

@end

@implementation DisclosureCell

@synthesize cellColor, shadowColor;

- (void)drawWithFrame:(NSRect)frame inView:(NSView *)view {
	[NSGraphicsContext saveGraphicsState];
	
	NSAffineTransform *transform = nil;
	if ([self isHighlighted] || [self state] == NSOnState) {
		CGFloat deltaX = NSWidth(frame)/2.0, deltaY = NSHeight(frame)/2.0;
		
		transform = [NSAffineTransform transform];
		[transform translateXBy:deltaX yBy:deltaY];
		[transform rotateByDegrees:([self isHighlighted] ? 45 : 90)];
		[transform translateXBy:-deltaX yBy:-deltaY];
		[transform concat];
	}
	
	NSRect buttonRect = SquareCenteredInRect(MIN(NSHeight(frame), NSWidth(frame)), frame);
		
	NSBezierPath *trianglePath = [NSBezierPath bezierPath];
	[trianglePath moveToPoint:NSMakePoint(NSMinX(buttonRect), NSMaxY(buttonRect))];
	[trianglePath lineToPoint:NSMakePoint(NSMaxX(buttonRect), (NSMaxY(buttonRect)/2.0))];
	[trianglePath lineToPoint:NSMakePoint(NSMinX(buttonRect), NSMinY(buttonRect))];
	[trianglePath closePath];
	
	NSShadow *shadow = [[NSShadow alloc] init];
	[shadow setShadowColor:shadowColor];
	[shadow setShadowOffset:NSMakeSize(([self state] == NSOnState ? 1 : 0), ([self state] == NSOffState ? -1 : 0))];
	[shadow setShadowBlurRadius:0];
	
	[shadow set];
	[([self isHighlighted] ? [cellColor blendedColorWithFraction:0.2 ofColor:[NSColor blackColor]] : cellColor) set];
	[trianglePath fill];
	
	[NSGraphicsContext restoreGraphicsState];
	[shadow release];
}

@end
